<template>
  <div class="closing">
    <div>
      <el-button size="mini" @click="handleGetUntreated">{{ $t('btn.reload') }}</el-button>
      <el-button type="primary" size="mini" @click="isClosingDialog=true">{{ $t('market.filter') }}</el-button>
      <el-button type="success" size="mini" @click="pushAdjust">
        {{ $t('menu.createAdjustment') }}<!--新增成本调整单 :disabled="!calcuNewly || bomCost('createFinCola')" -->
      </el-button>
      <el-button type="primary" size="mini" @click="introduce">成本维护引入单价</el-button>
      <el-button type="primary" size="mini" @click="handleExport">{{ $t('btn.toExcel') }}</el-button>
      <!--      <el-button type="primary" size="mini" @click="balance(1)">结存</el-button>-->
      <!--      <el-button type="primary" size="mini" @click="balance(2)">反结存</el-button>-->
      <!--      <el-button :loading="loading1" type="primary" size="mini" @click="wareCalculate">成本运算</el-button>-->
    </div>
    <div class="header">
      <div class="header-name">
        <span>{{ $t('market.period') }}</span>
        <el-input v-model="period" size="mini" disabled />
      </div>
      <!--      当前关账期间-->
      <dataRow ref="mainData" />
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        sortable
        table-selection
        :get-summaries="getSummaries"
        show-summary
        :selectable="checkboxInit"
        @selectionChange="selectionDatas"
      >
        <!--        <el-table-column type="selection" width="30px" align="center" :selectable="checkboxInit" />-->
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel1(col.scope.row.materialNumber)">
            {{ col.scope.row.materialNumber }}
          </el-link>
        </template>
        <!--   来源单ju    -->
        <template v-slot:tagSlot="col">
          <el-link type="primary" @click="pushFrombill(col.scope.row)">{{ col.scope.row.frombillNo }}</el-link>
        </template>
      </jc-table>
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="handleGetUntreated"
      />
    </div>
    <!-- 入库成本维护 -->
    <el-dialog
      v-dialogDrag
      :title="$t('menu.warehousingCosts')"
      model
      :visible.sync="isClosingDialog"
      :close-on-click-modal="false"
      width="600px"
      top="5vh"
      center
    >
      <div>
        <el-form :model="subDetails" size="mini" label-width="100px">
          <el-form-item :label="$t('market.checkDate')">
            <el-date-picker
              v-model="subDetails.period"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择月"
            />
          </el-form-item>
          <el-form-item :label="$t('market.frombillNunber')">
            <el-input v-model.trim="subDetails.frombillNo" />
          </el-form-item>
          <el-form-item :label="$t('market.fmaterial')">
            <el-input v-model.trim="subDetails.materialNumber" />
          </el-form-item>
          <el-form-item :label="$t('market.stockname')">
            <el-input v-model.trim="subDetails.stockName" />
          </el-form-item>
          <el-form-item :label="$t('shop.price1')">
            <el-input v-model.trim="subDetails.fsingleworth" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isClosingDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="initialCon">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 成本维护引入单价 -->
    <el-dialog
      v-dialogDrag
      :title="$t('market.cbyudj')"
      model
      :visible.sync="isIntrodDialog"
      :close-on-click-modal="false"
      width="400px"
      top="5vh"
      center
    >
      <el-radio-group v-model="bringInto">
        <el-radio v-for="item in incoming" :key="item.fid" :label="item.fid">
          {{ item.name }}
        </el-radio><br>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isIntrodDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="introducing">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryFinInstockMaintainList,
  antibalance, balance, tFinCostCollection, queryRedirectUrl, updateMaintainLPirce
} from '@/api/financial/warehousing'
import dataRow from '@/views/financial/company/components/dataRow'
import searData from '@/components/Search/mixin'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'

export default {
  name: 'WarehousingCosts',
  components: {
    dataRow
  },
  mixins: [searData],
  data() {
    return {
      subDetails: {
        period: '',
        stockName: '',
        materialNumber: '',
        frombillNo: '',
        fsingleworth: ''
      },
      bringInto: '',
      incoming: [
        { name: '期初加权平均价', fid: 1 },
        { name: '最新入库价', fid: 2 },
        { name: '最新出库价', fid: 3 },
        { name: '物料参考成本', fid: 4 },
        { name: '最新采购订单成本', fid: 5 }
      ],
      total: 0, // 总条目
      pageNum: 1, // 当前页
      pageSize: 200, // 每页显示多少条数据
      period: '',
      loading: false,
      loading1: false,
      isClosingDialog: false,
      isIntrodDialog: false,
      calcuNewly: true, // 是否可以运算 新增成本单
      // 表头
      selectData: [],
      tableData: [],
      tableHeight: '70vh',
      tableHeader: [
        { label: this.$t('market.frombillNunber'), type: 'tag', prop: 'frombillNo' },
        { label: this.$t('market.billType'), prop: 'billtypename' },
        { label: this.$t('shop.fname2'), prop: 'materialName' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'materialNumber', width: '120' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecification' },
        { label: this.$t('market.fqty'), prop: 'fqty', align: 'right', width: '80' },
        { label: this.$t('market.baseUnit'), prop: 'funitName', width: '80' },
        { label: this.$t('market.storageUnit'), prop: 'fpurunit', width: '80' },
        { label: this.$t('market.fprice'), prop: 'fsingleworth', align: 'right', width: '80' },
        { label: this.$t('market.billamount'), prop: 'fworth', align: 'right', width: '90' },
        { label: this.$t('market.updatesingleworth'), prop: 'fupdatesingleworth', align: 'right', width: '110' },
        { label: this.$t('market.updateworth'), prop: 'fupdateworth', align: 'right', width: '110' },
        { label: this.$t('market.stock2'), prop: 'stockName' },
        { label: this.$t('market.orderDate'), prop: 'fdate', width: '100' },
        { label: this.$t('shop.fdescripTion'), prop: 'fdescription', width: '200' }
      ]
    }
  },
  created() {
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 220px)' : '73vh'
  },
  methods: {
    // 过滤确认
    initialCon() {
      this.isClosingDialog = false
      const { period } = this.subDetails
      this.period = period
      this.handleGetUntreated()
    },
    // 表格选择框是否可选
    checkboxInit(row, index) {
      if (row.isedit === 1) {
        return 1 // 可勾选
      } else {
        return 0 // 不可勾选
      }
    },
    // 获取入库成本维护列表数据
    async handleGetUntreated() {
      /* 已存货关账期间 <= 期间 */
      this.calcuNewly = this.$refs.mainData.panyForm.nowMaintainDate <= this.period
      this.loading = true
      if (!this.period) {
        this.isClosingDialog = true
        this.loading = false
        return
      }
      const DATA = {
        ...this.subDetails,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }
      const RES = await queryFinInstockMaintainList(DATA)
      if (RES.code === 0) {
        this.loading = false
        this.tableData = RES.data.array
        this.total = RES.data.total
      } else {
        this.loading = false
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 来源单据跳转页面
    pushFrombill(ev) {
      const DATA = {
        fbillNo: ev.frombillNo,
        enumId: ev.billtype
      }
      queryRedirectUrl(DATA).then(res => {
        if (res.code === 0) {
          this.$router.push({ path: res.data.redirectUrl })
        }
      })
    },
    // 全选
    selectionDatas(val) {
      this.selectData = val
      this.listData = []
      val.forEach(res => {
        this.listData.push({
          fmaintainId: res.fmaintainId,
          billtype: res.billtype,
          ftablename: res.ftablename,
          in_tablename: res.in_tablename,
          fmaterialId: res.fmaterialId,
          billentryId: res.billentryId,
          fstockId: res.fstockId,
          fsingleworth: res.fsingleworth,
          fworth: res.fworth,
          fqty: res.fqty,
          in_worth: res.in_worth
        })
      })
    },
    // 新增成本调整单
    pushAdjust() {
      if (this.selectData.length === 0) {
        this.$message.warning('请选择数据.')
        return
      }
      this.$router.push({
        name: 'CreateAdjustment',
        params: {
          date: this.period,
          details: this.selectData,
          fid: 1248
        }
      })
    },
    // 结存 反结存
    balance(ev) {
      if (!this.period) return
      const api = ev === 1 ? balance : antibalance
      const DATA = {
        period: this.period
      }
      const message = ev === 1 ? '结存期间：' : '反结存期间：'
      this.$confirm(message + DATA.period, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        api(DATA).then(res => {
          if (res.code === 0) {
            this.$refs.mainData.queryCompany()
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 成本运算
    wareCalculate() {
      this.$confirm('是否确定进行期间:' + this.period + '的成本运算', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading1 = true
        tFinCostCollection({ period: this.period }).then(res => {
          if (res.code === 0) {
            this.loading1 = false
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.loading1 = false
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 成本维护引入单价
    introduce() {
      if (this.selectData.length === 0) {
        this.$confirm('请选择单据!!!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      } else {
        this.isIntrodDialog = true
      }
    },
    // 成本维护引入单价 确定
    introducing() {
      const DATA = {
        paicetype: this.bringInto,
        period: this.period,
        list: this.listData
      }
      updateMaintainLPirce(DATA).then(res => {
        if (res.code === 0) {
          this.isIntrodDialog = false
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          queryFinInstockMaintainList({
            pageSize: 100000,
            pageNum: 1,
            ...this.subDetails
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '入库成本维护')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.closing {
  @include listBom;
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-radio {
    display: block;
    padding: 5px 0;
  }
  .header{
    margin-top: 10px;
    .header-name{
      span {
        width: 100px;
        margin-right: 10px;
        text-align: right;
      }
    }
  }
}
</style>
